//
//  JXRefreshView.swift
//  swift高仿微博
//
//  Created by peijiaxing on 16/3/5.
//  Copyright © 2016年 peijiaxing. All rights reserved.
//

import UIKit
import SnapKit


enum RefreshType:Int{
    // 两种状态跳转之间的状态
    
    case Disapper = 3
    
    // 默认状态
    case Normal = 0
    // 下拉
    case Pulling = 1
    // 加载
    case Loading = 2
}


class JXRefreshView: UIControl {

    // 成员变量
    var scrollView: UIScrollView?
    // 记录一下状态
    var oldStatus: RefreshType = RefreshType.Normal
    
    var isLoading : Bool = false
    
    var status: RefreshType = RefreshType.Normal{
        didSet{
            switch status {
            case RefreshType.Normal : print("正常状态")
//            //箭头显示
            arrowImageView.hidden = false
//            //loading隐藏
            loadingImageView.hidden = true
            //提示
            messageLabel.text = "下拉刷新"
            
//            //改变箭头方向
            rotateArrowImageView(true)
//            //停止加载
            stopLoadingAnimation()
//                
            if isLoading{
                
//                showLoadingView(false)
                
                isLoading = false
                }

                
            case RefreshType.Pulling: print("下拉状态")
            //箭头显示
            arrowImageView.hidden = false
//            //loading隐藏
            loadingImageView.hidden = true
            //提示
            messageLabel.text = "释放刷新"
//            //改变箭头方向
            rotateArrowImageView(false)
//            
//            showLoadingView(true)
                
            case RefreshType.Loading : print("加载中")
            
//                //箭头隐藏
                arrowImageView.hidden = true
//                //loading转动
                loadingImageView.hidden = false
            
                messageLabel.text = "加载中........"
            
                startLoadingAnimation()
            
//                // 添加顶部可以多滑动的距离
//                showLoadingView(true)
//                //修改标记
                isLoading = true
            
                // 加载中 让视图在NAV 下边加载出来
                var inset = scrollView?.contentInset
                inset?.top = +64
                scrollView?.contentInset = inset!
            
                // 当状态改变的时候  发送一个时间
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
                // 记录加载状态
                oldStatus = RefreshType.Loading
           
            case .Disapper : break
            
            }
        
        }
        
    }
    
    
    // 加载完成
    func endRefreshing(){
        
        status = RefreshType.Normal
        if oldStatus == RefreshType.Loading{
            
        var inset = scrollView?.contentInset
            
            inset?.top = +64
            scrollView?.contentInset = inset!
            // 恢复标记
            oldStatus = .Normal
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = UIColor.yellowColor()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        var frame = self.frame
        
        // 修改frame
        
        
        frame.size = CGSizeMake(UIScreen.mainScreen().bounds.size.width, 64)
        
        frame.origin.y = -64
        self.frame = frame
        
        addSubview(messageLabel)
        addSubview(arrowImageView)
        addSubview(loadingImageView)
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowImageView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self.snp_centerY)
            make.right.equalTo(messageLabel.snp_left)
        }
        loadingImageView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImageView.snp_center)
        }
        
    }
    
    
    // 添加KVO 
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        scrollView = newSuperview as? UIScrollView
        
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        let scrollView = object as? UIScrollView
        
        // 判断位置并刷新
        
        if scrollView!.dragging{
            if scrollView?.contentOffset.y < -150 && status == .Normal {
                // 改变状态
                status = RefreshType.Pulling
                
            }else if scrollView?.contentOffset.y < -144 && scrollView?.contentOffset.y > -150 && status == .Pulling {
                
                status = RefreshType.Normal
            }
        }else {
           if scrollView?.contentOffset.y < -150 && status == RefreshType.Pulling{
             status = RefreshType.Loading
            }
            
        }
    }
    

    
    private lazy var messageLabel : UILabel  = {
       
        let label = UILabel()
        
        label.text = "下拉刷新"
        label.textColor = UIColor.redColor()
        label.font = UIFont.systemFontOfSize(15)
        
        return label
    }()
    
    // 箭头
    private lazy var arrowImageView :UIImageView = {
       let img = UIImageView()
        
        img.image = UIImage(named: "tableview_pull_refresh")
        
        return img
        
    }()
    
    // 加载的视图
    private lazy var loadingImageView: UIImageView = {
        let img = UIImageView()
        
        img.image = UIImage(named: "tableview_loading")
        
        img.hidden = true
        
        return img
        
    }()
    
    ///箭头转动动画
    private func rotateArrowImageView(flag:Bool){
        
        var angle = M_PI
        
        angle += flag ?  -0.01 : 0.01
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.arrowImageView.transform = CGAffineTransformRotate(self.arrowImageView.transform, CGFloat(angle))
        }
        
    }
    
    ///开启加载动画
    private func startLoadingAnimation(){
        
        let animamation = CABasicAnimation(keyPath: "transform.rotation")
        
        animamation.toValue = 2 * M_PI
        
        animamation.repeatCount = MAXFLOAT
        
        animamation.duration = 0.5
        
        loadingImageView.layer.addAnimation(animamation, forKey: nil)
        
    }
   
    ///停止动画
    private func stopLoadingAnimation(){
        
        loadingImageView.layer.removeAllAnimations()
        
    }
    

    
//    ///视图显示
//    private func showLoadingView(flag:Bool){
//        
//        UIView.animateWithDuration(0.25, animations: { () -> Void in
//            var contentInset = self.scrollView!.contentInset
//            flag ? (contentInset.top += self.frame.size.height) : (contentInset.top -= self.frame.size.height)
//            self.scrollView?.contentInset = contentInset
//        })
//        
//    }
    
}
